package com.demo.cloud.configuration;

import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * zuul 熔断处理者
 * 由原来的 ZuulFallbackProvider 变成 FallbackProvider
 */
@Component
public class MyFallbackProvider implements FallbackProvider {

    @Override
    public String getRoute() {
        // 返回 * 代表所有需要路由的服务，都添加熔断功能
        // 也可以指定服务名称
        // 多个怎么指定？？
//        return "*";
        return "service-1";
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() {
                // 熔断处理，表示服务异常
                return HttpStatus.INTERNAL_SERVER_ERROR;
            }

            @Override
            public int getRawStatusCode() {
                return 500;
            }

            @Override
            public String getStatusText() {
                return "INTERNAL_SERVER_ERROR";
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                // 返回提示信息
                return new ByteArrayInputStream("INTERNAL_SERVER_ERROR".getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                // 设置请求响应的head
                HttpHeaders httpHeaders = new HttpHeaders();
                httpHeaders.setContentType(MediaType.APPLICATION_JSON);
                return httpHeaders;
            }
        };
    }
}
